<template>
  <!--用户查询-->
  <userSearch :search-form="searchForm" @search="searchUsers" @reset="resetSearchUsers" />
  <!--新增用户按钮-->
  <div style="margin-bottom: 10px;"><el-button type="primary" @click="handleAddUser">新增用户</el-button></div>
  <!--用户列表-->
  <userTable :user-list="users" :isLoading = "isLoading" @edit="handleEditUser" @toggle-status="handleToggleStatus" @delete="handleDeleteUser" />
  <!--loading加载器-->
  <loaderDemo :isLoading = "isLoading"/>
  <!--用户列表分页-->
  <!-- <userPagination :pagination="pagination" @page-change="handlePageChangeV" @size-change="handleSizeChangeV" /> -->
  <userFormInfo v-model:visible="showDialog" :title="dialogTitle" :form-data="userForm" :rules="formRules"
    @submit="handleSaveUser" @cancel="handleCancelForm" @update:visible="dialogVisible = $event" />
  <!--父组件使用:visible="showDialog" @update:visible="showDialog = $event"进行双向绑定-->  
</template>

<script setup>
import { ref, watch, reactive, toRefs,onMounted } from 'vue'
import userTable from '@/components/user/userTable.vue'
import userSearch from '@/components/user/userSearch.vue'
import userPagination from '@/components/user/userPagination.vue'
import { useUsers } from '@/common/user/useUsers'
import { usePagination } from '@/common/user/usePagination'
import userFormInfo from '@/components/user/userFormInfo.vue'
import { user_GetSearchUsers_api } from '@/common/corewebapi/user_api'
import { useApiResponseCodeStore } from '@/store/apiResponseCode'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import loaderDemo from '@/components/until/loaderDemo.vue'

//用户数据和方法
//值使用storeToRefs保持响应式
const {
  users,//api返回用户实体
  searchForm,//api请求查询条件实体
  userForm//新增和修改用户实体
} = storeToRefs(useUsers());
//方法可以直接解构
const {
  addUser,//新增用户
  updateUser,//更新用户
  deleteUser,//删除用户
  toggleUserStatus,//切换用户状态
  resetuserForm,//重置表单
  filluserForm//填充表单数据
} = useUsers();
// 分页数据和方法
//值使用storeToRefs保持响应式
const {
  pagination//分页信息 
} = storeToRefs(usePagination());
//方法可以直接解构
const {
  paginateData,
  handlePageChange,
  handleSizeChange,
  resetPagination
} = usePagination();
const isLoading = ref(false);//是否启用加载器
const showDialog = ref(false);//弹出框状态(新增和修改用户的编辑框)
const dialogTitle = ref('新增用户');//弹出框标题(动态变换新增用户和编辑用户)
//新增和编辑用户表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realname: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
};
const apiResponseCodeStore = useApiResponseCodeStore().apiResponseCode;//api响应码枚举

//查询用户信息
function searchUsers() {  
  isLoading.value = true;  
  user_GetSearchUsers_api(searchForm.value).then((res) => {            
    let { code, msg, body } = res.data;
    if (code === apiResponseCodeStore.Success) {
      {
        users.value.splice(0, users.value.length, ...body.searches);//更新用户列表
        // 3秒后自动关闭
        setTimeout(() => {
          isLoading.value = false;
        }, 1500);        
      }      
    }
    else
    {
      isLoading.value = false;
      ElMessage.error(msg);//处理错误         
    }
               
  }).catch((error) => {
    isLoading.value = false;
    ElMessage.error(error.message);//处理错误
  });
}
// 处理重置搜索
function resetSearchUsers() {
  searchForm.value.username = '';
  searchForm.value.realname = '';
  console.log(searchForm.value)
  searchUsers();
}
// 处理添加用户
const handleAddUser = () => {
  dialogTitle.value = '新增用户';
  resetuserForm();//重置表单
  showDialog.value = true;
}
// 处理保存用户
const handleSaveUser = (userData) => {
  if (userData.id)
    updateUser(userData);//更新用户
  else
    addUser(userData);//新增用户

  handleSearch();//重新查询数据
}
// 处理取消表单
const handleCancelForm = () => {
  showDialog.value = false;//隐藏编辑页面
}
// 处理编辑用户
const handleEditUser = (user) => {
  dialogTitle.value = '编辑用户';
  filluserForm(user);
  showDialog.value = true;
}
// 处理切换用户状态
const handleToggleStatus = (user) => {
  toggleUserStatus(user);
  handleSearch();
}
// 处理删除用户
const handleDeleteUser = async (id) => {
  const success = await deleteUser(id);
  if (success) {
    handleSearch();
  }
}
// // 处理分页变化
// const handlePageChangeV = (page) => {
//   handlePageChange(page);
//   const paginatedData = paginateData(filteredUsers.value);
//   updateUsers(paginatedData);
// }
// // 处理每页条数变化
// const handleSizeChangeV = (size) => {
//   console.log("处理每页条数变化被调用");
//   pagination.pageSize = size;
//   pagination.currentPage = 1;
//   fetchUsers();
// }
</script>

<style scoped></style>